package com.lorizz.picpub.web.controller.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpSession;

import org.springframework.ui.Model;

import com.lorizz.picpub.query.UpmQueries;
import com.lorizz.picpub.util.Util;
import com.lorizz.picpub.web.Constants;
import com.lorizz.picpub.web.controller.UserHomeController;
import com.lorizz.upm.Album;
import com.lorizz.upm.ImageVariant;
import com.lorizz.upm.UserProfile;
import com.lorizz.upm.np.AlbumNP;
import com.lorizz.upm.np.ImageVariantNP;
import com.lorizz.upm.np.NPUtils;
import com.lorizz.upm.np.UserProfileNP;
import com.lorizz.upm.repository.Repository;

public class UserHomeControllerImpl implements UserHomeController {

	private Repository upmRepository;

	public void setUpmRepository(Repository upmRepository) {
		this.upmRepository = upmRepository;
	}

	@Override
	public String index(HttpSession session, String userAccount, Model model) {
		// TODO Auto-generated method stub
		UserProfileNP userProfileNP = (UserProfileNP) session
				.getAttribute(Constants.SESSION_USERPROFILE);
		Boolean showMain = false;
		String account = "";

		if (userProfileNP != null) {
			account = userProfileNP.getName();
			if (!Util.isNullOrEmpty(userAccount) && account.equals(userAccount) || Util.isNullOrEmpty(userAccount)) {
				showMain = true;
			}
		} else {
			account = userAccount;
		}

		model.addAttribute("showMain", showMain);
		if (!Util.isNullOrEmpty(account)) {
			Map<String, Object> albums = GetUserAlbum(account);
			for(Entry<String, Object> item :  albums.entrySet())
			{
				model.addAttribute(item.getKey(), item.getValue());
			}
			model.addAttribute("account", account);
		}
		return "dashboard";
	}

	private Map<String, Object> GetUserAlbum(String userAccount) {
		Map<String, Object> result = new HashMap<String, Object>();
		
		UserProfile userProfile = upmRepository
				.executeFirstOrDefault(UpmQueries.instance().userProfiles(
						userAccount));
		
		if (userProfile != null) {
			Long userProfileId = userProfile.getId();
			List<Album> albums = upmRepository.executeQuery(UpmQueries.instance().albums(userProfileId));
	        List<Object[]> albumIdsCounts1stImg = upmRepository.executeQuery(UpmQueries.instance()
	                .albumIdsWithImageCountsAnd1stImageId(userProfileId));
	        //
	        Map<Long, Long> imageCounts = new HashMap<Long, Long>();
	        for (Album album : albums) {
	            boolean found = false;
	            for (Object[] o : albumIdsCounts1stImg) {
	                if (album.getId().equals(o[0])) {
	                    found = true;
	                    imageCounts.put(album.getId(), (Long) o[1]);
	                    break;
	                }
	            }
	            if (!found) {
	                imageCounts.put(album.getId(), 0L);
	            }
	        }
	        //
	        List<Long> imgIds = new ArrayList<Long>();
	        for (Object[] o : albumIdsCounts1stImg) {
	            imgIds.add((Long) o[2]);
	        }
	        Map<Long, ImageVariantNP> imageVars = new HashMap<Long, ImageVariantNP>();
	        if (!imgIds.isEmpty()) {
	            List<Object[]> imgVars = upmRepository.executeQuery(UpmQueries.instance().imageVariantsWithImageIds(imgIds,
	                    "thumbnail.middle"));
	            for (Object[] o : imgVars) {
	                Long imgId = (Long) o[0];
	                for (Object[] o1 : albumIdsCounts1stImg) {
	                    if (imgId.equals(o1[2])) {
	                        imageVars.put((Long) o1[0], NPUtils.packageImageVariant((ImageVariant) o[1]));
	                        break;
	                    }
	                }
	            }
	        }
	        //
	        List<AlbumNP> albumNPs = NPUtils.packageAlbumList(albums);
	        for (AlbumNP albumNP : albumNPs) {
	            albumNP.setUserProfile(NPUtils.packageUserProfile(albums.get(0).getUserProfile()));
	        }
	        //
	        result.put("albums", albumNPs);
	        result.put("imageCounts", imageCounts);
	        result.put("imageVars", imageVars);
		}
		return result;
	}
	
	
}
